<?php
namespace Wap\Service;

use Home\Model\WechatUserModel;
use Wap\Model\PraiseItemRecordModel;

class WeixinService
{
    private static $prefix_wxuser = "wxuser_";//微信账号
    private static $expire_wxuser = 6300; //1.75h
    private static $table_wxuser = "wxuser";

    private static $user = "user";//微信用户

    private static $expire_jsapi_ticket = 6300;

    public static function setWxuser($key, $value)
    {
        $key = self::$prefix_wxuser . $key;
        S($key, $value, self::$expire_wxuser);
    }

    public static function getWxuser($key)
    {
        $exist = S(self::$prefix_wxuser . $key);

        if (!$exist) {
            $condition['token'] = $key;

            $exist = D(self::$table_wxuser)->where($condition)->cache('wap_wx' . $key, 60)->find();
            self::setWxuser($key, $exist);

            return $exist;
        }
        return $exist;
    }

    public static function setAccessToken($wxuser, $token)
    {
        return S($wxuser['appid'] . "_access_token", $token, self::$expire_wxuser);
    }

    public static function getAccessToken($wxuser)
    {
        $token = S($wxuser['appid'] . "_access_token");
        $check = S("check_access_token_" . $wxuser['token']);
        if (!$token && !$check) {
            S("check_access_token_" . $wxuser['token'], 1, 5);
            $uri = "https://api.weixin.qq.com/cgi-bin/token" . "?" . "appid=" . $wxuser['appid'] . "&" . "secret=" . $wxuser['appsecret'] . "&" . "grant_type=client_credential";
            $out = self::simpleGet($uri);
            $out = json_decode($out, 1);
            $token = isset($out['access_token']) ? $out['access_token'] : null;
            self::setAccessToken($wxuser, $token);
            S("check_access_token_" . $wxuser['token'], 0, 5);
        }
        return $token;
    }

    public static function setUser($appid = null, $appsecret = null, $code = null)
    {
        if ($code != null) {
            $uri = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $appsecret . "&code=" . $code . "&grant_type=authorization_code";
            $exist = self::simpleGet($uri);
            $exist = json_decode($exist, 1);
            $exist = isset($exist['openid']) ? $exist : null;
            session(self::$user . "11", $exist);
            return $exist;
        }
    }

    public static function getUser()
    {
        return session(self::$user . "11");
    }

    public static function getFollowStatus($user, $wxuser, $unionid, $need_follow)
    {
        //--2016/11/17暂时取消关注需求---
        if (empty($need_follow)) {
            return true;
        }
        $followed = 0;
        if (!$user || !$wxuser) {
            $followed = 0;
            return $followed;
        }
        //--20180831借权公众号判断是否已经关注--
        if (in_array($wxuser['token'], PraiseItemRecordModel::$token_arr)) {
            $cond['union_id'] = $unionid;
            $cond['ori_id'] = $wxuser['wxid'];
            $cond['status'] = WechatUserModel::STATUS_ACTIVE;
            $user1 = M("wechat_user")->where($cond)->find();
            if(empty($user1)){
                return 0;
            }else{
                return true;
            }
        }

        $token = self::getAccessToken($wxuser);
        if (empty($token)) {
            return -1;
        }
        $res = self::simpleGet("https://api.weixin.qq.com/cgi-bin/user/info" . "?" . "access_token=" . $token . "&" . "openid=" . $user['openid'] . "&lang=zh_CN");
        $res = json_decode($res, 1);
        if (isset($res['subscribe']) && $res['subscribe']) {
            $followed = true;
        } else {
            if (isset($res['errcode']) && $res['errcode'] == 40001) {
                $uri = "https://api.weixin.qq.com/cgi-bin/token" . "?" . "appid=" . $wxuser['appid'] . "&" . "secret=" . $wxuser['appsecret'] . "&" . "grant_type=client_credential";
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $uri);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                $out = curl_exec($ch);
                curl_close($ch);
                $out = json_decode($out, 1);
                $token = isset($out['access_token']) ? $out['access_token'] : null;
                WeixinService::setAccessToken($wxuser, $token);
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/user/info" . "?" . "access_token=" . $token . "&" . "openid=" . $user['openid'] . "&lang=zh_CN");
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                $out = curl_exec($ch);
                curl_close($ch);
                $res = json_decode($out, 1);
                if (isset($res['subscribe']) && $res['subscribe']) {
                    $followed = 1;
                } else {
                    $followed = 0;
                }
            } else if ($res['errcode'] == 40003) {
                $uri = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $wxuser['appid'] . "&secret=" . $wxuser['secret'] . "&code=" . $_GET['code'] . "&grant_type=authorization_code";
                $exist = self::simpleGet($uri);
                $exist = json_decode($exist, 1);
                $exist = isset($exist['openid']) ? $exist : null;
                session(self::$user, $exist);
                $res = self::simpleGet("https://api.weixin.qq.com/cgi-bin/user/info" . "?" . "access_token=" . $token . "&" . "openid=" . $exist['openid'] . "&lang=zh_CN");
                $res = json_decode($res, 1);
                if (isset($res['subscribe']) && $res['subscribe']) {
                    $followed = true;
                } else {
                    if (isset($res['errcode']) && $res['errcode'] == 40001) {
                        $uri = "https://api.weixin.qq.com/cgi-bin/token" . "?" . "appid=" . $wxuser['appid'] . "&" . "secret=" . $wxuser['appsecret'] . "&" . "grant_type=client_credential";
                        $ch = curl_init();
                        curl_setopt($ch, CURLOPT_URL, $uri);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                        $out = curl_exec($ch);
                        curl_close($ch);
                        $out = json_decode($out, 1);
                        $token = isset($out['access_token']) ? $out['access_token'] : null;
                        WeixinService::setAccessToken($wxuser, $token);
                        $ch = curl_init();
                        curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/user/info" . "?" . "access_token=" . $token . "&" . "openid=" . $exist . "&lang=zh_CN");
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                        $out = curl_exec($ch);
                        curl_close($ch);
                        $res = json_decode($out, 1);
                        if (isset($res['subscribe']) && $res['subscribe']) {
                            $followed = 1;
                        } else {
                            $followed = 0;
                        }
                    } else {
                        $followed = 0;
                    }
                }
            } else {
                $followed = 0;
            }
        }
        return $followed;
    }

    public static function setJSAPITicket($wxuser, $ticket)
    {
        if ($ticket != null) {
            S("jsapi_ticket_" . $wxuser['token'], $ticket, self::$expire_jsapi_ticket);
        }
    }

    public static function getJSAPITicket($wxuser)
    {
        $ticket = S("jsapi_ticket_" . $wxuser['token']);
        if (!$ticket) {
            $token = self::getAccessToken($wxuser);
            $uri = sprintf("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi", $token);
            $res = self::simpleGet($uri);
            $res = json_decode($res, 1);
            $ticket = isset($res['ticket']) ? $res['ticket'] : null;
            self::setJSAPITicket($wxuser, $ticket);
        }
        return $ticket;
    }

    public static function buildWXJSApi($wxuser, $url = '')
    {
        $api = array("ticket" => "", "sha1" => "", "timestamp" => time(), "noncestr" => "1234567890", "url" => "");
//        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $protocol = "http://";
        if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
            $protocol = "https://";
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
            $protocol = "https://";
        } elseif (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
            $protocol = "https://";
        }
        $api['url'] = $url ? $url : "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $api['ticket'] = self::getJSAPITicket($wxuser);
        //$api['ticket'] = 'kgt8ON7yVITDhtdwci0qeVVL02qyOPmn1GLjxVYeQqgksFfR42ykvV_952ThDy1OEjXRH5H8s_LmGfE1ZvTC4A';
        if (empty($api['ticket'])) {
            return $api['ticket'];
        }
        $wxOri = sprintf("jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s", $api['ticket'], $api['noncestr'], $api['timestamp'], $api['url']);
        $api['sha1'] = sha1($wxOri);
        return $api;
    }


    /**
     *函数名: build_snsbase
     *函数描述: build 微信静默授权网页链接
     * @param string $url 授权成功后跳转链接
     * @return string $result 微信oauth2 授权链接
     */
    public static function buildOauthURI($url, $appid, $scope = "snsapi_base")//should not here
    {
        $uri = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $appid . "&redirect_uri=" . urlencode($url) . "&response_type=code&scope=" . $scope . "&state=oauth#wechat_redirect";
        return $uri;
    }

    private static function simpleGet($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 500);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        $out = curl_exec($ch);
        curl_close($ch);
        return $out;
    }

    public static function snsapiUserInfoLink($url, $appid)
    {
        $uri = sprintf("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect", $appid, urlencode($url));
        return $uri;
    }
}

?>
